import { ref } from 'vue'

interface GameStats {
  totalGames: number
  wins: number
  losses: number
  draws: number
  averageMovesPerGame: number
  totalPlayTime: number
  rating: number
}

interface GameResult {
  winner: 'white' | 'black' | 'draw'
  moves: number
  playTime: number
}

export function useChessStats() {
  const stats = ref<GameStats>({
    totalGames: 0,
    wins: 0,
    losses: 0,
    draws: 0,
    averageMovesPerGame: 0,
    totalPlayTime: 0,
    rating: 1200
  })

  const loadStats = () => {
    const savedStats = localStorage.getItem('chessStats')
    if (savedStats) {
      stats.value = JSON.parse(savedStats)
    }
  }

  const saveStats = () => {
    localStorage.setItem('chessStats', JSON.stringify(stats.value))
  }

  const updateStats = (result: GameResult) => {
    stats.value.totalGames++
    stats.value.totalPlayTime += result.playTime

    switch (result.winner) {
      case 'white':
        stats.value.wins++
        stats.value.rating += 15
        break
      case 'black':
        stats.value.losses++
        stats.value.rating -= 15
        break
      case 'draw':
        stats.value.draws++
        stats.value.rating += 5
        break
    }

    stats.value.averageMovesPerGame = (
      (stats.value.averageMovesPerGame * (stats.value.totalGames - 1) + result.moves) /
      stats.value.totalGames
    )

    saveStats()
  }

  const resetStats = () => {
    stats.value = {
      totalGames: 0,
      wins: 0,
      losses: 0,
      draws: 0,
      averageMovesPerGame: 0,
      totalPlayTime: 0,
      rating: 1200
    }
    saveStats()
  }

  return {
    stats,
    loadStats,
    updateStats,
    resetStats
  }
} 